package com.qf.qfusermanager.web.controller;

import com.qf.common.bean.R;
import com.qf.common.dto.CmdParamDto;
import com.qf.common.dto.UserDto;
import com.qf.common.model.QfUser;
import com.qf.common.utils.JwtUtil;
import com.qf.qfusermanager.adapter.UserAdapter;
import com.qf.qfusermanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/auth/doLogin")
    public R login(@RequestBody QfUser userDto){
        System.out.println("------");

        String username = userDto.getUserName();
        String password = userDto.getPassword();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        //这行代码底层是UserDetailsService在处理业务。返回值返回的是UserDetails对象
        Authentication authenticate = authenticationManager.authenticate(authRequest);

        if (authenticate == null){
            //失败
            return R.fail(R.Code.FAILURE,"用户名或密码错误");
        }

        //成功
        //将成功后的jwt返回
        UserAdapter loginUser = (UserAdapter) authenticate.getPrincipal();
        String id = UUID.randomUUID().toString().replaceAll("-","");
        String subject = loginUser.getQfUser().getId() + "";//获取用户的id
        String jwt = JwtUtil.createJWT(id, subject, null);

        return R.ok(jwt);
    }

    @PostMapping("/cmd/send")
    public R send(@RequestBody(required = false) CmdParamDto cmdParamDto){
        return userService.send(cmdParamDto);
    }
}
